import java.util.Arrays;

public class Sieve {
    public static boolean[] sieve(int n) {
        if (n <= 2) {
            return new boolean[n]; // 默认false
        }
        boolean[] isPrime = new boolean[n];
        for (int i = 2; i < n; i++) {
            isPrime[i] = true;
        }
        int sqrt = (int) Math.sqrt(n) + 1;
        for (int i = 2; i < sqrt; i++) {
            if (isPrime[i]) {
                for (int j = i * i; j < n; j += i) {
                    isPrime[j] = false;
                }
            }
        }
        return isPrime;
    }

    public static void main(String[] args) {
        int n = args.length > 0 ? Integer.parseInt(args[0]) : 10_000_000;
        int runs = args.length > 1 ? Integer.parseInt(args[1]) : 5;
        boolean printFlag = args.length > 2; // 第三个参数存在则打印
        long totalTime = 0;

        // 预热运行
        for (int i = 0; i < 3; i++) {
            sieve(1_000_000);
        }
        
        for (int i = 0; i < runs; i++) {
            long start = System.nanoTime();
            boolean[] primes = sieve(n);
            long end = System.nanoTime();
            if (printFlag) {
                System.out.println(Arrays.toString(primes));
            }
            totalTime += (end - start);
        }

        double avgTime = (double) totalTime / 1_000_000 / runs;
        System.out.printf("Java   | %.2f ms\n", avgTime);
    }
}